import errorEvent from '../../errorMessage';
import store from '@/store/index'
const uuid = require('uuid');

let formatApiData = api => {
    api.id = api.apiId;
    api.apiFolderId = api.folderId;
    api.param = JSON.parse(api.param.replace(/\&apos\;/g, "'"));
    api.bodyType = api.param.bodyType;
    api.header = api.param.header;
    api.body = api.param.body;
    api.fromdata = api.param.fromdata;
    api.query = api.param.query;
    api.rest = api.param.rest;
    api.before = api.param.before;
    api.after = api.param.after;
    api.response = api.param.response;
    if (api.response === undefined) {
        api.response = JSON.stringify({
            key: '',
            type: 'object',
            model: {},
            annotate: '',
            children: [{
                key: '',
                type: '',
                model: {},
                annotate: '',
                children: [],
            }],
        })
    };
    return api;
};


export default {
    async getRenderData() {
        var projectId = store.state.mainOptions.project.projectId;
        var allFolder = `SELECT * FROM folder WHERE folder_project_id = '${projectId}' AND disable = 0 and type = 0`;
        var allApi = `SELECT * FROM project_api WHERE project_id = '${projectId}' AND disable = 0`;
        try {
            let folderList = await window.DB.find(allFolder);
            let apiList = await window.DB.find(allApi);
            for (let i = 0; i < folderList.length; i++) {
                const folderItem = folderList[i];
                folderItem.id = folderItem.folderId;
            };
            for (let i = 0; i < apiList.length; i++) {
                const api = apiList[i];
                formatApiData(api);
            };
            // console.log(apiList);
            return {
                apiList: apiList,
                folderList: folderList,
            };
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    async creatFolder(newFolder, parentFolder) {
        var _id = uuid.v1();
        var _create_time = new Date().getTime();
        var projectId = store.state.mainOptions.project.projectId;
        var sql = `INSERT INTO folder (
                folder_id,
                folder_project_id,
                folder_parent_id,
                title,
                description,
                type,
                disable,
                update_time, 
                create_time
                ) VALUES (
                '${_id}',
                '${projectId}',
                '${parentFolder.folderId}',
                '${newFolder.title.replace(/\'/g, "\'\'")}',
                '${newFolder.description.replace(/\'/g, "\'\'")}',
                0, 0,
                ${_create_time}, 
                ${_create_time});`;
        parentFolder.newFolderArray.push(_id);
        parentFolder.folderIndexArray = parentFolder.newFolderArray.join(';');
        // oldFolder
        var upDateFolderIndexSql = `
                UPDATE folder SET 
                folder_index_array = '${parentFolder.folderIndexArray}',
                update_time = ${_create_time}
                WHERE folder_id = '${parentFolder.folderId}';`;
        try {
            await window.DB.creat(sql);
            await window.DB.update(upDateFolderIndexSql);
            return newFolder;
        } catch (error) {
            errorEvent(error);
            return false;
        }
    },
    async updataFolderDetail(updateObj) {
        var time = new Date().getTime();
        var Sql = `
        UPDATE folder SET 
        title = '${updateObj.title.replace(/\'/g, "\'\'")}',
        description = '${updateObj.description.replace(/\'/g, "\'\'")}',
        update_time = ${time}
        WHERE folder_id = '${updateObj.id}';`;
        try {
            await window.DB.update(Sql);
            return true;
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    async updataFolderOrderByInto(updateObj) {
        var time = new Date().getTime();
        var fromSql = `
            UPDATE folder SET 
            folder_index_array = '${updateObj.fromFolder.index}',
            update_time = ${time}
            WHERE folder_id = '${updateObj.fromFolder.id}';`;
        var moveSql = `
            UPDATE folder SET 
            update_time = ${time},
            folder_parent_id = '${updateObj.moveFolder.parent}'
            WHERE folder_id = '${updateObj.moveFolder.id}';`;
        var toSql = `
            UPDATE folder SET 
            folder_index_array = '${updateObj.toFolder.index}',
            update_time = ${time}
            WHERE folder_id = '${updateObj.toFolder.id}';`;
        try {
            await DB.update(fromSql);
            await DB.update(moveSql);
            await DB.update(toSql);
            return true;
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    async updateFolderOrderBySame(updateObj) {
        var time = new Date().getTime();
        var Sql = `
            UPDATE folder SET 
            folder_index_array = '${updateObj.index}',
            update_time = ${time}
            WHERE folder_id = '${updateObj.id}';`;
        try {
            await DB.update(Sql);
            return true;
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    async deleteFolder(param) {
        var time = new Date().getTime();
        var SqlSelf = `
            UPDATE folder SET 
            disable = 1,
            update_time = ${time}
            WHERE folder_id = '${param.folderId}';`;
        var Sqlfolder = `
            UPDATE folder SET 
            folder_parent_id = '${param.parentId}',
            update_time = ${time}
            WHERE folder_parent_id = '${param.folderId}';`;
        var SqlApis = `
            UPDATE project_api SET 
            folder_id = '${param.parentId}',
            update_time = ${time}
            WHERE folder_id = '${param.folderId}';`;
        try {
            await DB.update(SqlSelf);
            await DB.update(Sqlfolder);
            await DB.update(SqlApis);
            return true;
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    async creatApi(param) {
        var _id = uuid.v1();
        var CT = new Date().getTime();
        var projectId = store.state.mainOptions.project.projectId;
        var sql = `INSERT INTO project_api (
            api_id,
            project_id,
            folder_id,
            title,
            type,
            disable,
            status,
            description,   
            url,
            param,
            update_time,
            create_time 
            ) VALUES (
            '${_id}',
            '${projectId}',
            '${param.folderId}',
            '${param.title.replace(/\'/g, "\'\'")}',
            '${param.type.replace(/\'/g, "\'\'")}',
            0,
            ${param.status},
            '${param.description.replace(/\'/g, "\'\'")}',
            '${param.url.replace(/\'/g, "\'\'")}',
            '${param.param.replace(/\'/g, "\'\'")}',
            ${CT}, 
            ${CT});`;
        param.oldApiArray.push(_id);
        param.childIndexArray = param.oldApiArray.join(';');

        var FolderSql = `
                UPDATE folder SET 
                child_index_array = '${param.childIndexArray}',
                update_time = ${CT}
                WHERE folder_id = '${param.folderId}';`;
        try {
            await window.DB.creat(sql);
            await window.DB.update(FolderSql);
            return _id;
        } catch (error) {
            errorEvent(error);
            return false;
        }
    },
    async updataApi(param) {
        var CT = new Date().getTime();
        var Sql = `
        UPDATE project_api SET 
        title = '${param.title.replace(/\'/g, "\'\'")}',
        type = '${param.type}',
        status = ${param.status},
        description = '${param.description.replace(/\'/g, "\'\'")}',   
        url = '${param.url.replace(/\'/g, "\'\'")}',
        param = '${param.param.replace(/\'/g, "\'\'")}',
        update_time = ${CT}
        WHERE api_id = '${param.id}';`;
        try {
            await window.DB.update(Sql);
            return true;
        } catch (error) {
            errorEvent(error);
            return false;
        }
    },
    async updataApiOrderBySame(param) {
        var time = new Date().getTime();
        var Sql = `
            UPDATE folder SET 
            child_index_array = '${param.index}',
            update_time = ${time}
            WHERE folder_id = '${param.id}';`;
        try {
            await DB.update(Sql);
            return true;
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    async updataApiOrderByDifferent(param) {
        var time = new Date().getTime();
        var SqlFrom = `
            UPDATE folder SET 
            child_index_array = '${param.from.index}',
            update_time = ${time}
            WHERE folder_id = '${param.from.id}';`;
        var SqlTo = `
            UPDATE folder SET 
            child_index_array = '${param.to.index}',
            update_time = ${time}
            WHERE folder_id = '${param.to.id}';`;
        var SqlApi = `
            UPDATE project_api SET 
            folder_id = '${param.to.id}',
            update_time = ${time}
            WHERE api_id = '${param.id}';`;
        try {
            await DB.update(SqlFrom);
            await DB.update(SqlTo);
            await DB.update(SqlApi);
            return true;
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    async deleteApi(id) {
        var time = new Date().getTime();
        var SqlApi = `
            UPDATE project_api SET 
            disable = 1,
            update_time = ${time}
            WHERE api_id = '${id}';`;
        try {
            await DB.update(SqlApi);
            return true;
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    async searchApi(str, type) {
        var projectId = store.state.mainOptions.project.projectId;
        var sql = `
        SELECT * FROM project_api 
        WHERE project_id = '${projectId}' 
        AND disable = 0 
        AND (url LIKE '%${str.replace(/\'/g, "\'\'")}%' OR title LIKE '%${str.replace(/\'/g, "\'\'")}%')`;
        if (type == 'ALL') {
            sql += ';';
        } else {
            sql += ` AND type = '${type}';`;
        };
        try {
            var apiList = await DB.find(sql);
            for (let i = 0; i < apiList.length; i++) {
                const api = apiList[i];
                formatApiData(api);
            };
            return apiList;
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
}